<template>
  <div class="other-diagnosis">
    <div class="header">
      <h2>其他诊断</h2>
      <div class="header-actions">
        <div class="patient-info" v-if="selectedPatient">
          <span class="patient-tag">患者：{{ selectedPatient.name }} ({{ selectedPatient.identityNumber }})</span>
          <button @click="clearPatient" class="btn-clear">切换为全局模式</button>
        </div>
        <div v-else class="mode-actions">
          <button @click="openPatientDialog" class="btn-select-patient">选择患者</button>
          <span class="mode-info">当前：全局疾病模式</span>
        </div>
      </div>
    </div>
    <div class="search-bar">
      <input 
        v-model="search" 
        :placeholder="selectedPatient ? '搜索患者其他诊断...' : '搜索疾病名称...'" 
        class="input" 
        @keyup.enter="handleSearch"
      />
      <button @click="handleSearch" class="btn" :disabled="loading">
        {{ loading ? '搜索中...' : '搜索' }}
      </button>
    </div>
    
    <div class="table-info">
      <span v-if="selectedPatient" class="info-text">
        患者其他诊断 ({{ diagnoses.length }} 条)
      </span>
      <span v-else class="info-text">
        全部疾病 (第{{ page }}页，共{{ totalPages }}页，{{ total }}条记录)
      </span>
    </div>
    
    <table class="diagnosis-table">
      <thead>
        <tr>
          <th>序号</th>
          <th>诊断编码</th>
          <th>诊断名称</th>
          <th>国际ICD编码</th>
          <th>疾病类型</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="item in diagnoses" :key="item.id || item.index" :class="{ 'patient-disease': selectedPatient }">
          <td>{{ item.index }}</td>
          <td>{{ item.code }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.icd }}</td>
          <td>{{ item.type }}</td>
          <td>
            <button 
              v-if="selectedPatient && item.canDelete" 
              @click="handleAdd(item)" 
              class="btn-delete"
            >
              删除
            </button>
            <button 
              v-else 
              @click="handleAdd(item)" 
              class="btn-add"
            >
              选择
            </button>
          </td>
        </tr>
        <tr v-if="diagnoses.length === 0">
          <td colspan="6" class="no-data">
            {{ loading ? '加载中...' : (selectedPatient ? '该患者暂无其他诊断' : '暂无疾病数据') }}
          </td>
        </tr>
      </tbody>
    </table>
    
    <div class="pagination" v-if="!selectedPatient && totalPages > 1">
      <button @click="prevPage" :disabled="page === 1" class="btn">上一页</button>
      <span class="page-info">第 {{ page }} 页 / 共 {{ totalPages }} 页</span>
      <button @click="nextPage" :disabled="page === totalPages" class="btn">下一页</button>
    </div>
    
    <!-- 患者选择对话框 -->
    <div v-if="showPatientSelectDialog" class="dialog-overlay" @click="showPatientSelectDialog = false">
      <div class="dialog" @click.stop>
        <div class="dialog-header">
          <h3>选择患者</h3>
          <button class="btn-close" @click="showPatientSelectDialog = false">×</button>
        </div>
        <div class="dialog-body">
          <div class="search-row">
            <input 
              v-model="patientSearchKeyword" 
              class="form-input" 
              placeholder="输入患者姓名搜索..." 
              @keyup.enter="searchPatients"
            />
            <button class="btn primary" @click="searchPatients">搜索</button>
          </div>
          <div class="patient-list">
            <div 
              v-for="patient in availablePatients" 
              :key="patient.patientId" 
              class="patient-item"
              @click="selectPatient(patient)"
            >
              <div class="patient-name">{{ patient.name }}</div>
              <div class="patient-info-detail">{{ patient.idCard }} | {{ patient.gender }}</div>
            </div>
            <div v-if="availablePatients.length === 0" class="no-data">
              {{ patientLoading ? '搜索中...' : '未找到患者' }}
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import eventBus from '@/utils/eventBus'
import { 
  pageQueryDiseases,
  searchDiseasesByName,
  getPatientDiseases,
  deletePatientDisease,
  pageQueryInsuredPerson
} from '@/api/admission'

const search = ref('')
const diagnoses = ref([])
const selectedPatient = ref(null)
const loading = ref(false)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 患者选择相关
const showPatientSelectDialog = ref(false)
const patientSearchKeyword = ref('')
const availablePatients = ref([])
const patientLoading = ref(false)

// 加载数据
async function loadData() {
  if (selectedPatient.value) {
    await loadPatientDiseases()
  } else {
    await loadAllDiseases()
  }
}

// 加载所有疾病（分页）
async function loadAllDiseases() {
  loading.value = true
  try {
    const response = await pageQueryDiseases({
      pageNum: page.value,
      pageSize: pageSize.value,
      name: search.value.trim() || undefined
    })
    
    if (response.flag && response.data) {
      const records = response.data.records || []
      diagnoses.value = records.map((item, index) => ({
        id: item.id,
        index: (page.value - 1) * pageSize.value + index + 1,
        code: item.diseaseCode || item.code || '-',
        name: item.diseaseName || item.name || '-',
        icd: item.icdCode || item.icd || '-',
        type: '疾病',
        canDelete: false
      }))
      total.value = response.data.total || 0
    } else {
      diagnoses.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载疾病数据失败:', error)
    ElMessage.error('加载疾病数据失败')
    diagnoses.value = []
  } finally {
    loading.value = false
  }
}

// 加载患者疾病（仅其他诊断）
async function loadPatientDiseases() {
  if (!selectedPatient.value?.patientId) return
  
  loading.value = true
  try {
    const response = await getPatientDiseases(selectedPatient.value.patientId)
    if (response.flag && response.data) {
      // 过滤其他诊断（次要诊断）
      const patientDiseases = response.data.filter(item => item.isPrimary === 0) || []
      diagnoses.value = patientDiseases.map((item, index) => ({
        id: item.id,
        index: index + 1,
        code: item.diseaseCode || '-',
        name: item.diseaseName || '-',
        icd: item.icdCode || '-',
        type: '其他诊断',
        canDelete: true,
        patientDiseaseId: item.id
      }))
      total.value = diagnoses.value.length
    } else {
      diagnoses.value = []
      total.value = 0
    }
  } catch (error) {
    console.error('加载患者疾病失败:', error)
    ElMessage.error('加载患者疾病失败')
    diagnoses.value = []
  } finally {
    loading.value = false
  }
}

function handleSearch() {
  if (selectedPatient.value) {
    // 患者模式下的本地搜索 - 重新加载患者疾病然后过滤
    loadPatientDiseases().then(() => {
      const keyword = search.value.trim()
      if (keyword) {
        const allDiseases = [...diagnoses.value] // 保存完整列表
        const filtered = allDiseases.filter(d => 
          d.name.includes(keyword) || d.code.includes(keyword)
        )
        diagnoses.value = filtered
      }
    })
  } else {
    // 全局模式下使用API搜索
    const keyword = search.value.trim()
    if (keyword && keyword.length >= 2) {
      searchDiseasesByAPI(keyword)
    } else {
      // 如果搜索词为空或太短，重新加载全部数据
      page.value = 1
      loadAllDiseases()
    }
  }
}

// 新增：使用API搜索疾病
async function searchDiseasesByAPI(keyword) {
  loading.value = true
  try {
    const response = await searchDiseasesByName(keyword)
    if (response.flag && response.data) {
      const records = response.data || []
      diagnoses.value = records.map((item, index) => ({
        id: item.id,
        index: index + 1,
        code: item.diseaseCode || item.code || '-',
        name: item.diseaseName || item.name || '-',
        icd: item.icdCode || item.icd || '-',
        type: '疾病',
        canDelete: false
      }))
      total.value = records.length
    } else {
      diagnoses.value = []
      total.value = 0
      ElMessage.info('未找到相关疾病')
    }
  } catch (error) {
    console.error('搜索疾病失败:', error)
    ElMessage.error('搜索疾病失败')
    diagnoses.value = []
    total.value = 0
  } finally {
    loading.value = false
  }
}

watch(search, (val) => {
  if (!val.trim()) {
    // 搜索框清空时恢复数据
    if (selectedPatient.value) {
      loadPatientDiseases()
    } else {
      page.value = 1
      loadAllDiseases()
    }
  }
})

async function handleAdd(row) {
  if (selectedPatient.value && row.canDelete) {
    await handleDelete(row)
  } else {
    eventBus.emit('addOtherDiagnosis', row)
    ElMessage.success(`已选择诊断：${row.name}`)
  }
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm(
      `确定要删除其他诊断"${row.name}"吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const response = await deletePatientDisease(row.patientDiseaseId)
    if (response.flag) {
      ElMessage.success('删除成功')
      await loadPatientDiseases()
      eventBus.emit('refreshPatientDiseases')
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error === 'cancel') return
    console.error('删除失败:', error)
    ElMessage.error('删除失败')
  }
}

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

function prevPage() {
  if (page.value > 1) {
    page.value--
    loadAllDiseases()
  }
}

function nextPage() {
  if (page.value < totalPages.value) {
    page.value++
    loadAllDiseases()
  }
}

function handlePatientSelected(patient) {
  selectedPatient.value = patient
  search.value = ''
  page.value = 1
  loadData()
}

function handlePatientCleared() {
  selectedPatient.value = null
  search.value = ''
  page.value = 1
  loadData()
}

// 患者选择相关函数
async function searchPatients() {
  patientLoading.value = true
  try {
    const response = await pageQueryInsuredPerson({
      pageNum: 1,
      pageSize: 20,
      name: patientSearchKeyword.value.trim() || undefined
    })
    
    if (response.flag && response.data) {
      availablePatients.value = response.data.records || []
    } else {
      availablePatients.value = []
    }
  } catch (error) {
    console.error('搜索患者失败:', error)
    ElMessage.error('搜索患者失败')
    availablePatients.value = []
  } finally {
    patientLoading.value = false
  }
}

function selectPatient(patient) {
  selectedPatient.value = {
    ...patient,
    identityNumber: patient.idCard // 确保字段一致
  }
  showPatientSelectDialog.value = false
  search.value = ''
  page.value = 1
  loadData()
  ElMessage.success(`已选择患者：${patient.name}`)
}

function clearPatient() {
  selectedPatient.value = null
  search.value = ''
  page.value = 1
  loadData()
  ElMessage.info('已切换为全局疾病模式')
}

// 打开患者选择对话框时加载默认患者列表
function openPatientDialog() {
  showPatientSelectDialog.value = true
  patientSearchKeyword.value = ''
  searchPatients() // 加载默认患者列表
}

onMounted(() => {
  loadData()
  eventBus.on('patientSelected', handlePatientSelected)
  eventBus.on('patientCleared', handlePatientCleared)
})

onUnmounted(() => {
  eventBus.off('patientSelected', handlePatientSelected)
  eventBus.off('patientCleared', handlePatientCleared)
})
</script>

<style scoped>
.other-diagnosis {
  padding: 24px;
  background: #fff;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 16px;
}

.header h2 {
  margin: 0;
  color: #2c3e50;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 14px;
}

.mode-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.mode-info {
  color: #909399;
  font-size: 13px;
}

.patient-tag {
  background: #e3f2fd;
  color: #1976d2;
  padding: 4px 12px;
  border-radius: 16px;
  font-size: 13px;
}

.btn-select-patient {
  background: #67c23a;
  color: #fff;
  border: none;
  padding: 6px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: background 0.2s;
}

.btn-select-patient:hover {
  background: #5daf34;
}

.btn-clear {
  background: #e6a23c;
  color: #fff;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background 0.2s;
}

.btn-clear:hover {
  background: #cf9236;
}

.search-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.input {
  flex: 1;
  max-width: 300px;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.input:focus {
  outline: none;
  border-color: #409eff;
}

.btn {
  padding: 8px 16px;
  background: #409eff;
  color: #fff;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.btn:hover:not(:disabled) {
  background: #3a8ee6;
}

.btn:disabled {
  background: #c0c4cc;
  cursor: not-allowed;
}

.table-info {
  margin-bottom: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

.info-text {
  color: #606266;
  font-size: 14px;
  font-weight: 500;
}

.diagnosis-table {
  width: 100%;
  border-collapse: collapse;
  flex: 1;
  min-height: 300px;
}

.diagnosis-table th,
.diagnosis-table td {
  border: 1px solid #ebeef5;
  padding: 12px 8px;
  text-align: center;
  font-size: 14px;
}

.diagnosis-table th {
  background: #f5f7fa;
  color: #606266;
  font-weight: 600;
}

.diagnosis-table tbody tr:hover {
  background: #f5f7fa;
}

.diagnosis-table tbody tr.patient-disease {
  background: #fafafa;
}

.diagnosis-table tbody tr.patient-disease:hover {
  background: #e8f4fd;
}

.btn-add {
  background: #67c23a;
  color: #fff;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-add:hover {
  background: #5daf34;
}

.btn-delete {
  background: #f56c6c;
  color: #fff;
  border: none;
  padding: 4px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.btn-delete:hover {
  background: #f24c4c;
}

.no-data {
  color: #909399;
  font-style: italic;
  background: #fafafa;
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
}

.page-info {
  color: #606266;
  font-size: 14px;
}

/* 对话框样式 */
.dialog-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.dialog {
  background: white;
  border-radius: 8px;
  width: 500px;
  max-width: 90vw;
  max-height: 70vh;
  overflow: hidden;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  background: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
}

.dialog-header h3 {
  margin: 0;
  color: #34495e;
  font-size: 16px;
}

.btn-close {
  background: none;
  border: none;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background 0.2s;
}

.btn-close:hover {
  background: #e9ecef;
}

.dialog-body {
  padding: 20px;
  max-height: 50vh;
  overflow-y: auto;
}

.search-row {
  display: flex;
  gap: 10px;
  margin-bottom: 16px;
}

.form-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
}

.form-input:focus {
  outline: none;
  border-color: #409eff;
}

.btn.primary {
  background: #409eff;
  color: #fff;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn.primary:hover {
  background: #3a8ee6;
}

.patient-list {
  max-height: 300px;
  overflow-y: auto;
}

.patient-item {
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.patient-item:hover {
  background: #e3f2fd;
  border-color: #2196f3;
}

.patient-name {
  font-size: 14px;
  color: #34495e;
  font-weight: 500;
  margin-bottom: 4px;
}

.patient-info-detail {
  font-size: 12px;
  color: #999;
}

.patient-item:hover .patient-name {
  color: #2196f3;
}
</style> 